package edu.yzu.testspringboot002.config;


import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


//这个配置 中  minioClient销毁的时候，在哪里处理 还没弄清楚  先暂时不管
@Configuration
@Slf4j
public class MinioConfig {


    @Value("${minio.bucketName:mychatfile}")
    private String bucktName;

    @Value("${minio.url:}")
    private String minioUrl;
    @Value("${minio.access-key:}")
    private String minioKey;

    @Value("${minio.secret-key:}")
    private String minioSercet;


    @Bean
    public MinioClient minioClient() {

        log.info("minio start init {} -{} -{} -{}", bucktName, minioUrl, minioKey, minioSercet);

        MinioClient minioClient = MinioClient.builder()
                .credentials(minioKey, minioSercet)
                .endpoint(minioUrl)
                .build();
        afterPropertiesSet(minioClient);
        return minioClient;
    }


    public void afterPropertiesSet(MinioClient minioClient) {
        try {
            boolean bucketExists = minioClient.bucketExists(BucketExistsArgs.builder()
                    .bucket(bucktName)
                    .build());
            if (!bucketExists) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucktName).build());
            }
        } catch (Exception exception) {
            log.error("检查失败：{}", exception.getLocalizedMessage(), exception);
        }

    }
}
